/*
  This program will print a horizontal histogram of word lengths in a program

*/
#include <stdio.h>

#define IN  1
#define OUT 0
#define MAX_WORD_LENGTH  32

int main ()
{

  char string [16] = "silly.txt";
  /* word_length[5] = 7, means that there were 7 words of length 5; */
  int word_lengths [MAX_WORD_LENGTH];

  /* initialize word_lengths to 0 */
  for (int i = 0; i < MAX_WORD_LENGTH; i++)
    word_lengths[i] = 0;


  FILE * stream = fopen (string, "r");

  /* nw == new word */
  /* wl == word length */
  int c, nw, wl, state = 0;

  while ((c = fgetc (stream)) != EOF)
    {
      /* if this is NOT a word, state is now OUT of word */
      if (c == '\n' || c == ' ' || c == '\t')
        {
          state = OUT;
          /* this is a bug...why does wl eventually == 32,000? */
          if (wl > 0 && wl < MAX_WORD_LENGTH) 
            {
              word_lengths[wl] = word_lengths[wl] + 1;
            }
          wl = 0;
        }
      else //state is now IN a word
        {
          if (state == OUT)
            {
              state = IN;
              ++nw;
            }
          ++wl;
        }
    }

  printf ("%s has %d words\n", string, nw);

  //print the histogram of word lengths
  //ie:
  /* word_lengths = {0, 1, 4, 5}
     output is :

     1 -
     2 ----
     3 -----
  */

  for (int i = 1; i < MAX_WORD_LENGTH; i++)
    {
      if (word_lengths[i])
        {
          printf("%d ", i);
          for (int j = 0; j < word_lengths[i]; j++)
            fputc ('-', stdout);
          printf("\n");
        }
    }

  return 0;
}
